package com.ruoyi.web.lifecycle.started;

import com.ruoyi.common.base.ai.mapper.AIApiKeyMapper;
import com.ruoyi.common.base.ai.vo.AIApiKeyCache;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.exception.ServiceException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 启动后预热缓存数据
 *
 * @author gdk
 * @since 2022/8/12 16:12
 */
@Slf4j
@Order(0)
@Component
@AllArgsConstructor
public class AIWarmUpCache implements ApplicationRunner {

    private final AIApiKeyMapper apiKeyMapper;
    private final RedisTemplate<String, Object> redis;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 预热ApiKey
        initAIApiKey();
    }

    /**
     * 预热ApiKey
     *
     * @author gdk
     * @since 2022/9/29 12:32
     */
    private void initAIApiKey() {
        List<AIApiKeyCache> list = apiKeyMapper.listCache();
        if (CollectionUtils.isEmpty(list)) {
            throw new ServiceException("没有查询到任何可用的ApiKey信息");
        }

        redis.delete(CacheConstants.AI_API_KEY_HASH_KEY);
        redis.opsForSet().add(CacheConstants.AI_API_KEY_HASH_KEY, list.toArray());
        System.err.printf("预热ChatGPT的ApiKey条数：%s%n", list.size());
    }
}
